package cn.mianshiyi.braumdatasource.nacos;


import cn.mianshiyi.braumclient.ratelimit.LimitRuleConfig;
import cn.mianshiyi.braumclient.utils.EasyStringUtil;
import cn.mianshiyi.braumdatasource.AbstractDataSource;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.Listener;
import com.alibaba.nacos.api.exception.NacosException;

import java.util.List;
import java.util.Properties;
import java.util.concurrent.Executor;

/**
 * @author shangqing.liu
 */
public class NacosDataSource extends AbstractDataSource {
    private String groupId;
    private String dataId;
    private String serverAddr;
    private ConfigService configService;

    public NacosDataSource(String groupId, String dataId, String serverAddr) throws NacosException {
        this.groupId = groupId;
        this.dataId = dataId;
        this.serverAddr = serverAddr;
        if (EasyStringUtil.isEmpty(groupId) || EasyStringUtil.isEmpty(dataId) || EasyStringUtil.isEmpty(serverAddr)) {
            throw new IllegalArgumentException(String.format("nacos argument is not allow null: groupId=[%s], " +
                            "dataId=[%s], serverAddr=[%s]",
                    groupId, dataId, serverAddr));
        }
        Properties properties = new Properties();
        properties.put("serverAddr", serverAddr);
        ConfigService configService = NacosFactory.createConfigService(properties);
        this.configService = configService;
        configService.addListener(dataId, groupId, new Listener() {
            @Override
            public void receiveConfigInfo(String configInfo) {
                List<LimitRuleConfig> limitRuleConfigs = JSON.parseObject(configInfo,
                        new TypeReference<List<LimitRuleConfig>>() {
                        });
                NacosDataSource.super.updateConfig(limitRuleConfigs);
            }

            @Override
            public Executor getExecutor() {
                return null;
            }
        });
        //初始化外部规则
        initConfig();
    }

    @Override
    protected List<LimitRuleConfig> loadAllConfig() {
        try {
            String configInfo = configService.getConfig(dataId, groupId, 5000);
            return JSON.parseObject(configInfo,
                    new TypeReference<List<LimitRuleConfig>>() {
                    });
        } catch (NacosException e) {
            e.printStackTrace();
        }

        return null;
    }

}
